package com.crossriver.crgis.portlet;
import java.io.FileInputStream;
import java.io.IOException;
import javax.jms.MessageEOFException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.crossriver.crgis.database.model.Bank_Payment_Slip;
import com.crossriver.crgis.database.model.Transactions;
import com.crossriver.crgis.database.service.Bank_Payment_SlipLocalServiceUtil;
import com.crossriver.crgis.database.service.TransactionsLocalServiceUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.util.Base64;
import com.liferay.portal.kernel.util.CalendarFactoryUtil;
import com.liferay.portal.kernel.util.CalendarUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.User;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.util.bridges.mvc.MVCPortlet;

/**
 * Portlet implementation class Messages
 */
public class FETransactions extends MVCPortlet {
	
	// logger
	private static Log log = LogFactory.getLog(FETransactions.class);

	
	
	public void showTransaction(ActionRequest actionRequest,
			ActionResponse actionResponse) {
		if (log.isInfoEnabled()) {
			log.info("In  showTransaction ");
		}
		
		String transid = ParamUtil.getString(actionRequest, "transid");
		//Transactions transaction = new TransactionsLocalServiceUtil();
		//transaction=null;
		try {
			//List<Transactions> tempTransactions = TransactionsLocalServiceUtil.getTransactions(msgId);]
			
			if (log.isInfoEnabled()) {
				log.info("showing >>" + transid);
			}
			
			Transactions transaction = TransactionsLocalServiceUtil.getTransactions(transid);
			if (log.isInfoEnabled()) {
				log.info("In  Transaction " + transaction);
			}
			String viewTransactionJSP = "/html/transactions/viewTransaction.jsp";
			actionRequest.setAttribute("jspPage", viewTransactionJSP);
			actionResponse.setRenderParameter("jspPage", viewTransactionJSP);
			
			actionRequest.setAttribute("transaction", transaction);
			
		} catch (PortalException e) {
			
			if(log.isDebugEnabled()){
				log.debug("There is a problem retrieving transaction  >>>" + transid);	
			}
			
			SessionErrors.add(actionRequest, "problem-retrieving-transaction ");
			
			e.printStackTrace();
			return;
		} catch (SystemException e) {
			if(log.isDebugEnabled()){
				log.debug("There is a problem retrieving transaction  >>>" + transid);	
			}
			
			SessionErrors.add(actionRequest, "problem-retrieving-transaction ");
			
			e.printStackTrace();
			return;
		}
		
	}
	
	
	@Override
	public void serveResource(
			ResourceRequest resourceRequest, ResourceResponse resourceResponse)
		throws IOException, PortletException {
		String res = "";
		String queryType= ParamUtil.getString(resourceRequest, "queryType");
		String emailAddress =ParamUtil.getString(resourceRequest, "emailAddress");
		String userId =ParamUtil.getString(resourceRequest, "userId");
		ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest
		.getAttribute(WebKeys.THEME_DISPLAY); 
		
		JSONObject jsonFeed = JSONFactoryUtil.createJSONObject();
		
		User user = null;
		if (queryType.equalsIgnoreCase("viewPaymentSlip")){
			//
			System.out.println("doing >>>> " + queryType);
			String slipNo = ParamUtil.getString(resourceRequest, "slipNo");
			
			//retrieve the info 
			try {
				Bank_Payment_Slip bankSlip = Bank_Payment_SlipLocalServiceUtil.getBank_Payment_Slip(slipNo);
				
				
				resourceResponse.setProperty("Content-Disposition", "attachment; filename=" + bankSlip.getUploadDepositSlipFilename());
	        	
				
				byte[] readStream = Base64.decode(bankSlip.getUploadDepositSlip());
	    		
				resourceResponse.setProperty("Content-Disposition", "attachment; filename=" + bankSlip.getUploadDepositSlipFilename() );
	        	
				resourceResponse.getPortletOutputStream().write(readStream);
	    		
	    		return;
			} catch (PortalException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SystemException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return;
		}else if (queryType.equalsIgnoreCase("userId")){
			try {
				user = UserLocalServiceUtil.getUserByUuid(userId);
			} catch (PortalException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SystemException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.print("Email User Output>>>>>" + user);
			if (user == null){
				jsonFeed.put("emailMessage", "Email Does Not Exist");
				jsonFeed.put("emailFound", "0");
			}else{
				jsonFeed.put("emailMessage", "Email Address Exists");
				jsonFeed.put("email", user.getEmailAddress());
				jsonFeed.put("emailFound", "1");
			}
		}
	else
		{
			try {
				user = UserLocalServiceUtil.getUserByEmailAddress(themeDisplay.getCompanyId(),emailAddress);
			} catch (PortalException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SystemException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.print("Email User Output>>>>>" + user);
			if (user == null){
				jsonFeed.put("emailMessage", "Email Does Not Exist");
				jsonFeed.put("emailFound", "0");
			}else{
				jsonFeed.put("emailMessage", "Email Address Exists");
				jsonFeed.put("userId", user.getUserId());
				jsonFeed.put("emailFound", "1");
			}
		}
		
		res = "'{\"result\":true,\"count\":1}'";
		resourceResponse.setContentType("text/html");
		
		System.out.println(jsonFeed.toString());
		resourceResponse.getWriter().println(jsonFeed.toString());
	}
	/**
	 * This method is used to override the addSuccessMessage in the parent
	 * class. This override ensures that success message (that is displayed as
	 * default whenever any request is successfully submitted) is prevented.
	 * 
	 * We like to have control over this and this what this override ensures.
	 * 
	 */
	@Override
	protected void addSuccessMessage(ActionRequest actionRequest,
			ActionResponse actionResponse) {

		if (!addProcessActionSuccessMessage) {
			return;
		}
	}
}
